import { authorizationBehavior } from "../../behaviors/authorization";
import api from "../../common/api";
import constant from "../../common/constant";

const app = getApp();
let gioUser, gioFromId;
const DEFAULT_AVATAR = "https://media.shulanfd.com/static/jjrjs/img/default_avatar.png";

Page({
  behaviors: [authorizationBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    needShowEdit: false,
    btnTitle: "微信授权登录",
    type: "",
    isGetNumber: false,
    isgetHead: false,
    title: "",
    canIUseGetUserProfile: false,
    inviteImg: "https://media.shulanfd.com/static/jjrjs/active/laborDay.jpg",
    phoneImg: app.globalData.cdnResourceUrl + "middle/invite.png",
    listImgs: [],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.loginPromise.then(() => {
      api.getAppletSharingInfo({ refCode: "loginBg" }, ({ data }) => {
        this.setData({
          listImgs: data.content.list,
        });
      });
    });

    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }

    if (options.needShowEdit && options.needShowEdit == 1) {
      this.setData({
        needShowEdit: true,
      });
    }

    if (options.btnTitle) {
      this.setData({
        btnTitle: options.btnTitle,
      });
    }
    if (options.type) {
      this.setData({
        type: options.type,
      });
    }
    let mobile = app.globalData.sessionUser.mobile;

    if (options.title) {
      wx.setNavigationBarTitle({
        title: options.title,
      });
    }
    if (!mobile) {
      this.setData({
        isGetNumber: true,
      });
    } else {
      this.setData({
        // isGetNumber: true,
        isgetHead: true,
      });
    }
  },
  getPhoneNumber(e) {
    let locaUserInfo = wx.getStorageSync("user") || {};
    gioUser = wx.getStorageSync("currentCity");
    gioFromId = wx.getStorageSync("fromUserId");
    wx.gio("track", constant.Agree_Phone, {
      [constant.City_Ppl]: gioUser.city,
      [constant.InviteId_Ppl]: gioFromId,
      result_msg: e.detail.errMsg,
      token: wx.getStorageSync("tokenString"),
    });
    if (!e || !e.detail) return;
    const encryptedData = e.detail.encryptedData,
      iv = e.detail.iv;
    if (
      e.detail.errMsg == "getPhoneNumber:fail user deny" ||
      e.detail.errMsg == "getPhoneNumber:user deny" ||
      e.detail.errMsg == "getPhoneNumber:fail:cancel to confirm login"
    ) {
      try {
        wx.gio("track", "authMobile", {
          result_msg: e.detail.errMsg,
        });
      } catch (error) {}
    } else {
      api.bindWechatMobile(
        {
          encryptedData: encryptedData,
          iv: iv,
        },
        (res) => {
          try {
            wx.gio("track", "authMobile", {
              wechat_openid: locaUserInfo.openId,
              wechat_unionid: locaUserInfo.unionid,
              result_msg: res.data.successMessage || res.data.errorMessage,
              phone: res.data.content.mobile,
            });
          } catch (error) {}
          if (res && res.data && res.data.content && res.data.content.mobile) {
            app.assignSession({ mobile: res.data.content.mobile });
            if (this.data.needShowEdit) {
              app.globalData.needShowEdit = 1;
            }
            this.setData({
              isGetNumber: false,
              isgetHead: true,
            });
          }
        }
      );
    }
  },
  onGetUserInfo() {
    let t = this;
    wx.getUserProfile({
      lang: "zh_CN",
      desc: "用户个人中心展示",
      success: (res) => {
        t.userInfoHandler(res);
      },
      fail(err) {
        console.log("取消授权", err);
      },
    });
  },

  userInfoHandler(res) {
    wx.showLoading({ title: "加载中..." });

    let t = this;
    console.log("用户资料====>>>", res);
    gioUser = wx.getStorageSync("currentCity");
    gioFromId = wx.getStorageSync("fromUserId");

    wx.gio("track", constant.Agree_Wechat, {
      [constant.Phone]: app.globalData.sessionUser.extProps.wxMobile || app.globalData.sessionUser.mobile,
      [constant.City_Ppl]: gioUser.city,
      [constant.InviteId_Ppl]: gioFromId,
      result_msg: res.errMsg,
      token: wx.getStorageSync("tokenString"),
    });
    
    if (!(res && res.userInfo)) return wx.hideLoading();
    let { avatarUrl, city, country, gender, nickName, province } = res.userInfo || {};
    avatarUrl = avatarUrl || DEFAULT_AVATAR || "";
    let locaUserInfo = wx.getStorageSync("user") || {};
    api.complementUserInfo(
      {
        avatarUrl,
        city,
        country,
        gender,
        nickName,
        province,
        unionId: locaUserInfo.unionid,
        openId: locaUserInfo.openId,
      },
      (res1) => {
        try {
          wx.gio("track", "authWechat", {
            result_msg: res1.data.successMessage || res1.data.errorMessage,
            phone: app.globalData.sessionUser.mobile,
            wechat_nickname: nickName,
            wechat_avatar: avatarUrl,
            wechat_city: city,
            wechat_openid: locaUserInfo.openId,
            wechat_unionid: locaUserInfo.unionid,
          });
        } catch (error) {}
        if (res1 && res1.data && res1.data.isSuccess) {
          wx.setStorageSync(
            "user",
            Object.assign(locaUserInfo, {
              nickname: nickName,
              wxHeadImg: avatarUrl,
            })
          );
          api.settingEdit(
            {
              nickname: nickName || "",
              wxHeadImg: avatarUrl || "",
              city: city || "",
            },
            () => {
              wx.hideLoading();
              api.getSessionInfo(null, (res2) => {
                app.updateSessionUser(res2.data.content);

                const { authorTodoList } = app.globalData
                if (authorTodoList && authorTodoList.length) {
                  authorTodoList.forEach((fn) => fn())
                  authorTodoList.length = 0
                }
                
                if (t.data.type == "addHouseMethod") {
                  wx.redirectTo({
                    url: "/pages/gatherHouse/addHouseMethod/addHouseMethod",
                  });
                } else {
                  app.globalData.offlineRedPaperFlag = 3;
                  app.appGotoNextPage();
                }

              });
            }
          );
        }
      }
    );
  },

  // 兼容pc端
  getUserInfo(e) {
    console.log("用户资料getUserInfo====>>>", e.detail);

    this.userInfoHandler(e.detail);
  },
  noLogin() {
    app.appGotoNextPage(() => {
      wx.redirectTo({
        url: "/pages/index/index",
      });
    });
  },


});
